package com.jams.goodox.activity.serve.meet;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hangzhou.jin.customview.LoadView;
import com.hangzhou.jin.customview.SpaceItemDecoration;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.constant.Constants;
import com.jams.goodox.entity.MeetDateBean;
import com.jams.goodox.entity.MeetSessionBean;
import com.jams.goodox.entity.MeetSessionItemBean;
import com.jams.goodox.entity.MeetSureOrderBean;
import com.jams.goodox.entity.resp.MeetSessionResp;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 选择场次页面
 * Created by jams_zhen on 2017/5/8.
 */

public class MeetChooseSessionActivity extends BaseActivity {
    @Bind(R.id.tx_yesterday)
    TextView txYesterday;
    @Bind(R.id.tx_tomorrow)
    TextView txTomorrow;
    @Bind(R.id.tx_show_day)
    TextView txShowDay;
    @Bind(R.id.recycle_session)
    RecyclerView recycleSession;
    @Bind(R.id.loadView)
    LoadView loadView;

    private RecycleCommonAdapter recycleCommonAdapter;

    private MeetSessionBean meetSessionBean;

    private List<MeetSessionItemBean> meetSessionTimeList;//所有的会议场次列表
    private List<MeetSessionItemBean> chooseSessionTimeList;//执行下一步，选择的场地列表

    private String id;//场地id

    private MeetDateBean meetDateBean;
    private String subId;
    private String busId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_meet_choose_session;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this,"请选择场次");
        String chooseDate = getIntent().getStringExtra("chooseDate");
        if(TextUtils.isEmpty(chooseDate))chooseDate= Utils.getNowDate();

        id=getIntent().getStringExtra("id");
        subId=getIntent().getStringExtra("subId");
        busId=getIntent().getStringExtra("busId");

        meetSessionTimeList=new ArrayList<>();
        chooseSessionTimeList=new ArrayList<>();
        recycleSession.setLayoutManager(new LinearLayoutManager(this));
        recycleCommonAdapter=new RecycleCommonAdapter<MeetSessionItemBean>(this,meetSessionTimeList,R.layout.item_meet_session) {
            @Override
            public void convert(RecycleCommonViewHolder helper, final MeetSessionItemBean item, int position) {
                ImageView imgCheck=helper.getView(R.id.img_session_check);
                TextView txTime=helper.getView(R.id.tx_session_duration);
                TextView txCompany=helper.getView(R.id.tx_session_company);

                imgCheck.setImageResource(item.isCheck()?R.mipmap.check_theme:R.mipmap.un_check_gray);
                txTime.setText(item.getSessionDurationTime());
                txCompany.setText(item.getEnterpriseName());

                if(item.isReserve()){//如果场地已被预定
                    if(TextUtils.isEmpty(item.getEnterpriseName()))txCompany.setText("已过期，不可预定");
                    txCompany.setVisibility(View.VISIBLE);
                    imgCheck.setVisibility(View.GONE);
                    txTime.setTextColor(ContextCompat.getColor(MeetChooseSessionActivity.this,R.color.font_color_gray));
                    helper.setBackground(R.id.relative_item,R.drawable.bg_cancel_gray_meet);
                }else {//如果场地未被预定
                    txCompany.setVisibility(View.GONE);
                    imgCheck.setVisibility(View.VISIBLE);
                    if(item.isCheck()){
                        txTime.setTextColor(ContextCompat.getColor(MeetChooseSessionActivity.this,R.color.orange));
                    }else {
                        txTime.setTextColor(ContextCompat.getColor(MeetChooseSessionActivity.this,R.color.font_color_black));
                    }
                    helper.setBackground(R.id.relative_item,R.drawable.bg_cancel_white);
                }
                helper.setOnItemClickListener(new OnRecycleItemClickListener() {
                    @Override
                    public void itemClick() {
                        if(!item.isReserve()){
                            item.setCheck(!item.isCheck());
                            recycleCommonAdapter.notifyDataSetChanged();
                        }
                    }
                });

            }
        };
        recycleSession.setAdapter(recycleCommonAdapter);
        recycleSession.addItemDecoration(new SpaceItemDecoration(DensityUtil.dp2px(this,10f)));

        getData(chooseDate);
    }

    private void getData(final String placeDate) {
        loadView.loading();
        enqueue(createCallService(ServiceService.class).getDatePlaceList(id, placeDate), new RetrofitCallbackListener<MeetSessionResp>() {
            @Override
            public void onSuccess(Call<MeetSessionResp> call, MeetSessionResp result) {
                loadView.loadComplete();
                if (result.getData() == null) return;
                result.getData().setDateStr(placeDate);
                result.getData().setPlaceId(id);
                meetSessionBean=result.getData().transform();
                setData();
            }

            @Override
            public void onError(String msg) {
                loadView.loadComplete();
                ToastUtil.show(msg);
                loadView.loadCompleteNoData(R.mipmap.holder_no_meet_session,"今天没有场次可预约，去看看其他时间吧");//报错显示占位图
            }
        });
    }

    /**
     * 设置数据
     */
    private void setData(){
        txShowDay.setText(meetSessionBean.getShowDayStr());
        if(!meetSessionBean.isCanGoLeft()){
            txYesterday.setTextColor(ContextCompat.getColor(this,R.color.font_color_gray));
            txYesterday.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this,R.mipmap.meet_session_left_gray),null,null,null);
            txYesterday.setEnabled(false);
        }else {
            txYesterday.setTextColor(ContextCompat.getColor(this,R.color.font_color_black));
            txYesterday.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this,R.mipmap.meet_session_left),null,null,null);
            txYesterday.setEnabled(true);
        }
        meetSessionTimeList.clear();
        if(meetSessionBean.getMeetSessionTimeList().size()>0){
            meetSessionTimeList.addAll(meetSessionBean.getMeetSessionTimeList());
            recycleCommonAdapter.notifyDataSetChanged();
        }else {
            loadView.loadCompleteNoData(R.mipmap.holder_no_meet_session,"今天没有场次可预约，去看看其他时间吧");
        }

    }

    @OnClick({R.id.tx_yesterday, R.id.tx_tomorrow, R.id.frame_show_day,R.id.tx_next_step})
    public void onViewClicked(View view) {
        if(meetSessionBean==null)return;
        switch (view.getId()) {
            case R.id.tx_yesterday:
                getData(meetSessionBean.getLeftDate());
                break;
            case R.id.tx_tomorrow:
                getData(meetSessionBean.getRightDate());
                break;
            case R.id.frame_show_day:
                Intent in=new Intent(this,MeetCalendarActivity.class);
                in.putExtra("id",id);
                if (meetSessionBean != null) {
                    meetDateBean = new MeetDateBean();
                    meetDateBean.setFormatDate(meetSessionBean.getPlaceDate());
                    in.putExtra("meetDateBean", meetDateBean);
                }
                startActivityForResult(in, 101);
                break;
            case R.id.tx_next_step://下一步
                goNext();
                break;
        }
    }

    /**
     * 此处逻辑不清，产品待定
     */
    private void goNext(){
        if(meetSessionBean.getMeetSessionTimeList()==null||meetSessionBean.getMeetSessionTimeList().size()==0)return;//当列表为空，覆盖下一步，并类似去除点击事件
        getChooseItem();
        if(chooseSessionTimeList.size()==0){
            ToastUtil.show("未选择预定场次");
            return;
        }
        String strJson = new Gson().toJson(chooseSessionTimeList);
        Map<String,String> params=new HashMap<>();
        params.put("scheduleInfoList",strJson);
        params.put("subId",subId);
        showLoading();
        enqueue(createCallService(ServiceService.class).getPlaceOrder(params), new RetrofitCallbackListener<MeetSureOrderBean>() {
            @Override
            public void onSuccess(Call<MeetSureOrderBean> call, MeetSureOrderBean result) {
                misLoading();
                if(result.getData()==null||meetSessionBean==null|| result.getData().getScheduleOrder()==null)return;
                result.getData().setPlaceDate(meetSessionBean.getPlaceDate());
                result.getData().getScheduleOrder().setPlaceId(id);
                MeetPartOrderSureActivity.startFromMeet(MeetChooseSessionActivity.this,result.getData(), Constants.MEET_CODE,subId,busId);
            }

            @Override
            public void onError(String msg) {
                misLoading();
                ToastUtil.show(msg);
            }
        });

    }

    /**
     * 获取选中的所有场次
     */
    private void getChooseItem(){
        chooseSessionTimeList.clear();
        for (MeetSessionItemBean meetSessionTime:meetSessionTimeList){
            if(meetSessionTime.isCheck()){
                chooseSessionTimeList.add(meetSessionTime);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == RESULT_OK) {
            meetDateBean = (MeetDateBean) data.getSerializableExtra("meetDateBean");
            if (meetDateBean != null) getData(meetDateBean.getFormatDate());
        }
    }
}
